﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using MAnt3.Properties;
using System.Net;
using System.ComponentModel;
using System.Globalization;
using System.Configuration;
using System.Reflection;
using System.Windows.Documents;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using MAntLibrary;

namespace MAnt3
{
    public partial class MoznostiWindow
    {
        #region PROMENNE

        readonly Konfigurace konfigurece;
        readonly MainWindow mainwindow;
        private readonly IOproudy ioproudy;
       
        Microsoft.Win32.OpenFileDialog dlg;
        FolderBrowserDialog fileBrowserDialog;
        string cestaKzaloze;
        string nazevSlozky;
        string cestaKobnovovacimusouboru;

        Nullable<bool> result;
        public List<string> seznamMazanychSouboru;
        public List<string> seznamUpravenychKategorii;

        BackgroundWorker bw1,bw2;
        string cesta;

        // seznam parametru NetDirectu
        private Dictionary<int, string> parametryNetDirect;
        #endregion

        #region KONSTRUKTOR
        public MoznostiWindow(Konfigurace k, MainWindow mw, IOproudy io)
        {
            konfigurece = k;
            mainwindow = mw;
            ioproudy = io;

            InitializeComponent();

            nazevSlozky = "\\Zaloha " + DateTime.Now.ToString("yyyy-MM-dd (hh-mm-ss)", CultureInfo.InvariantCulture);
            cesta = string.Format(konfigurece.Ftp1Host + "//" + konfigurece.Ftp1PathXml);

            // BackgroundWorker 1 Vypis souboru z FTP
            bw1 = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = false };
            bw1.DoWork += bw1_DoWork;
            bw1.RunWorkerCompleted += bw1_Completed;
            bw1.ProgressChanged += bw1_Progress;

            // BackgroundWorker 2 pro vytvoreni zalohy
            bw2 = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = false };
            bw2.DoWork += bw2_DoWork;
            bw2.RunWorkerCompleted += bw2_Completed;
            bw2.ProgressChanged += bw2_Progress;

            // inicializuju parametry
            InicializaceParametruNetDirect();

            obnovitBTN.IsEnabled = false;
            label8.Content = string.Empty;
            label9.Content = string.Empty;
            pgLabel.Content = string.Empty;
            label10.Content = string.Empty;
            label101.Content = string.Empty;
            label6.Content = string.Empty;
            lbl001.Content = string.Empty;
            zalohovat.IsEnabled = false;
            cestaKzaloze = string.Empty;
            cestaKobnovovacimusouboru = string.Empty;
            progressBar1.Visibility = Visibility.Hidden;
            seznamMazanychSouboru = new List<string>();
            seznamUpravenychKategorii = new List<string>();

            // znepristupnim nektere zalozky
            itemParovani.IsEnabled = false;
            itemSpravaDB.IsEnabled = false;
            itemDodavatele.IsEnabled = true;
            
        }
        #endregion

        #region B A C K G R O U N D   W O R K E R 1
        public void bw1_DoWork(object sender, DoWorkEventArgs e)
        {
            pripojeniNaFTP();
        }

        public void bw1_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) 
            {
                //pgLabel.Content = "Zrusili jste praci"; 
            }
            else if (e.Error != null) 
            { 
                //pgLabel.Content = "vyskystla se vyjiska: " + e.Error; 
            }
            else
            {
                pgLabel.Content = string.Empty;
                progressBar1.Visibility = Visibility.Hidden;
                button6.Content = "Obnovit";

                foreach (string s in seznamMazanychSouboru)
                {
                    listView1.Items.Add(s);
                }
            }
        }

        public void bw1_Progress(object sender, ProgressChangedEventArgs e)
        {
            string N = Convert.ToString(e.UserState);

            switch (N)
            {
                case "MSG1":
                    listView1.Items.Clear();
                    progressBar1.Visibility = Visibility.Visible;
                    progressBar1.Value = 100;
                    pgLabel.Content = "Připojuji se...";
                    break;

                case "ERR1":
                    label9.Content = "Špatné přihlašovací údaje.";
                    button6.Content = "Připojit";
                    listView1.Items.Clear();
                    break;

                case "ERR2":
                    label9.Content = "Složka neobsahuje žádné soubory.";
                    break;
            }
        }
        #endregion

        #region B A C K G R O U N D   W O R K E R 2
        public void bw2_DoWork(object sender, DoWorkEventArgs e)
        {
            zalohuj();
        }

        public void bw2_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                //pgLabel.Content = "Zrusili jste praci"; 
            }
            else if (e.Error != null)
            {
                //pgLabel.Content = "vyskystla se vyjiska: " + e.Error; 
            }
            else
            {
                informacniTB.Text += "\nZálohování dokončeno.";
            }
        }

        public void bw2_Progress(object sender, ProgressChangedEventArgs e)
        {
            string I = e.ProgressPercentage.ToString();

            switch (I)
            {
                case "1":
                    informacniTB.Text += "soubor: " + e.UserState.ToString() + "\tzalohován.\n";
                    break;

                case "2":
                    informacniTB.Text += e.UserState.ToString();
                    break;
            }
        }
        #endregion

        #region FTP
        // smaze soubory z FTP
        private void button5_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in listView1.SelectedItems)
            {
                try
                {
                    FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create(textBox2.Text + textBox4.Text + item.ToString());
                    requestFileDelete.Credentials = new NetworkCredential(textBox1.Text, passwordBox1.Password.ToString());
                    requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;

                    FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
                }
                catch
                {
                    continue;
                }
            }
            
            // spustim backgroundworkera
            bw1.RunWorkerAsync();
        }

        // smaze vsechny soubrory
        private void button7_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in listView1.Items)
            {
                try
                {
                    FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create(textBox2.Text + textBox4.Text + item.ToString());
                    requestFileDelete.Credentials = new NetworkCredential(textBox1.Text, passwordBox1.Password.ToString());
                    requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;

                    FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
                }
                catch
                {
                    continue;
                }
            }

            // spustim backgroundworkera
            cesta = string.Format(textBox2.Text +"//"+ textBox4.Text);
            bw1.RunWorkerAsync();
        }

        // pripojeni na FTP
        private void button6_Click(object sender, RoutedEventArgs e)
        {
            label9.Content = string.Empty;

            // spustim backgroundworkera
            bw1.RunWorkerAsync();
        }

        // metoda vykonavajici pripojeni na FTP
        public void pripojeniNaFTP()
        {
            seznamMazanychSouboru = new List<string>();
            bw1.ReportProgress(0, "MSG1");

            string path = string.Format(@"{0}{1}", konfigurece.Ftp1Host, konfigurece.Ftp1PathXml); 
            
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);

                request.Credentials = new NetworkCredential(konfigurece.Ftp1User, konfigurece.Ftp1Psw);
                request.Method = WebRequestMethods.Ftp.ListDirectory;

                Stream r;
                WebResponse w;
                
                //(w = request.GetResponse())
                
                if (File.Exists((r = request.GetResponse().GetResponseStream()).ToString()))
                {
                    request.Abort();
                    return;
                }
                
                using (StreamReader streamReader = new StreamReader(r))
                {
                    string fileName = streamReader.ReadLine();

                    while (fileName != null)
                    {
                        seznamMazanychSouboru.Add(fileName);
                        fileName = streamReader.ReadLine();
                    }
                }
                request.Abort();
                
            }
            catch(WebException e)
            {
                bw1.ReportProgress(0, "ERR1");
                return;   
            }
        }
        #endregion

        #region DODAVATELE
        private void cmbDodavatele_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            txtDodavatele.Text = Dodavatel.getSleva(cmbDodavatele.SelectedItem.ToString());
        }

        private void txtDodavatele_TextChanged(object sender, TextChangedEventArgs e)
        {
            int sleva = 0;
            if (int.TryParse(txtDodavatele.Text, out sleva))
            {
                lblWarning.Content = "";
                Dodavatel.editDodavatele(cmbDodavatele.SelectedItem.ToString(), sleva);
            }
            else
            {
                lblWarning.Content = "Zadej celé číslo!";
            }
            
        }
        #endregion

        #region KATEGORIE

        private void btn1_Click(object sender, RoutedEventArgs e)
        {
            Nullable<bool> result;
            Microsoft.Win32.OpenFileDialog dlg;

            dlg = new Microsoft.Win32.OpenFileDialog();
            result = dlg.ShowDialog();
            string path;

            if (result == true)
            {
                tbx1.Text = dlg.FileName;
                path = dlg.FileName;
                nacistKategorie(path);
            }
        }

        private void nacistKategorie(string path)
        {
            // vymazu seznam kategorii
            Kategorie.resetKategorii();

            using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0"))
            {
                try
                {
                    con.Open();
                    string listname = "Kategorie";

                    //Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference
                    DataSet myDataSet = new DataSet();
                    OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [" + listname + "$]", con);
                    myCommand.Fill(myDataSet);
                    con.Close();
                    //richTextBox1.AppendText("\nDataSet Filled");

                    //Travers through each row in the dataset
                    foreach (DataRow myDataRow in myDataSet.Tables[0].Rows)
                    {
                        //Stores info in Datarow into an array
                        Object[] cells = myDataRow.ItemArray;
                        Kategorie.setKategorie( cells[0].ToString(), cells[3].ToString());
                    }
                }
                catch (Exception ex)
                {
                    label8.Content = "Chybný soubor";
                    return;
                }
            }

            // naplnim data do komponenty
            listBox1.Items.Clear();
            foreach (Kategorie k in Kategorie.getKategorie(true))
            {
                listBox1.Items.Add( k.Id + ": " + k.JmenoKategorie);
            }
            label8.Content = string.Empty;
            //listBox2.Items.Clear();
        }

        //private void nacistKategorie2(string path)
        //{

        //    Excel.Application eApp;
        //    Excel.Worksheet wSheet;
        //    Excel.Workbook wBook;


        //    string file = "file.xls";
        //    eApp = new Excel.Application();
        //    wBook = eApp.Workbooks.Open(file);
        //    wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1);

        //    wBook.SaveAs("asjdfkasfl.xsl");
        //}

        //private void releaseObject(object obj)
        //{
        //    try
        //    {
        //        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        //        obj = null;
        //    }
        //    catch (Exception ex)
        //    {
        //        obj = null;
        //        System.Windows.MessageBox.Show("Unable to release the Object " + ex.ToString());
        //    }
        //    finally
        //    {
        //        GC.Collect();
        //    }
        //}

        //
        // nahoru o jedno
        //
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            int index = listBox1.SelectedIndex;
            if (index != -1)
            {
                if (index > 0)
                {
                    var lbi = listBox1.Items[index];
                    listBox1.Items.RemoveAt(index);
                    index--;
                    listBox1.Items.Insert(index, lbi);
                    listBox1.SelectedIndex = index;
                    listBox1.ScrollIntoView(lbi);
                }
            }
            listBox1.SelectedItems.Clear();
        }

        //
        // na prvni misto
        //
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            int TOP = 0;
            int couter = listBox1.SelectedItems.Count;

            // smazu vybrane itemy z jejich aktualnich pozic
            // a vlozim je na pozici novou
            for (int i = 0; i < couter; couter--)
            {
                var itemA = listBox1.SelectedItems[i];
                listBox1.Items.Remove(itemA);
                listBox1.Items.Insert(TOP, itemA);
                TOP++;
            }
            listBox1.ScrollIntoView(0);
        }

        // 
        // dolu o jedno
        //
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            int index = listBox1.SelectedIndex;
            if (index != -1)
            {
                if (index < listBox1.Items.Count - 1)
                {
                    var listboxlbi = listBox1.Items[index];
                    listBox1.Items.RemoveAt(index);
                    index++;
                    listBox1.Items.Insert(index, listboxlbi);
                    listBox1.SelectedIndex = index;
                    listBox1.ScrollIntoView(listboxlbi);
                }
            }
        }

        //
        // na posledni misto
        //
        private void button8_Click(object sender, RoutedEventArgs e)
        {
            int DOWN = listBox1.Items.Count-1;
            int couter = listBox1.SelectedItems.Count;

            // smazu vybrane itemy z jejich aktualnich pozic
            // a vlozim je na pozici novou
            for (int i = 0; i < couter; couter--)
            {
                var itemA = listBox1.SelectedItems[i];
                listBox1.Items.Remove(itemA);
                listBox1.Items.Insert(DOWN, itemA);
                DOWN--;
            }
            listBox1.ScrollIntoView(listBox1.Items.Count-1);
        }
        #endregion

        #region OK BUTTON
        private void Bok_Click(object sender, RoutedEventArgs e)
        {
            // ulozim zmenene udaje
            uloz();
            moznostiWindow.Hide();

            // metoda ktera aktualizuje komponenty a hodnoty, ktere mohly byt zmeneny
            mainwindow.PozdniInicializace();
        }
        #endregion

        #region ULOZENI NASTAVENI
        private void uloz()
        {
            // ulozim FTP
            konfigurece.Ftp1User = textBox1.Text;
            konfigurece.Ftp1Psw = passwordBox1.Password.ToString(); 
            konfigurece.Ftp1Host = textBox2.Text;
            
            //ulozim kategorie
            List<string> ls = new List<string>();
            foreach (string s in listBox1.Items)
            {
                ls.Add(s);
            }
            Kategorie.setKategorie(ls);
            
            // ulozim dodavatele
            // dodavatele nemusim ukladat jsou jiz nastaveny aktualni hodnoty

            // ulozim zmeny v Settings
            konfigurece.ulozKonfiguraci();
        }
        #endregion

        #region Nacteni Nastaveni
        private void tabControl1_Loaded(object sender, RoutedEventArgs e)
        {
            // FTP
            textBox1.Text = konfigurece.Ftp1User;
            passwordBox1.Password = konfigurece.Ftp1Psw;
            textBox2.Text = konfigurece.Ftp1Host;
            textBox3.Text = konfigurece.Ftp1PathPictures;
            textBox4.Text = konfigurece.Ftp1PathXml;

            // KATEGORIE
            foreach (Kategorie k in Kategorie.getKategorie(true))
            {
                listBox1.Items.Add( k.Id+ ":  " +k.JmenoKategorie);
            }
            
            // PAROVANI
            labelDodavatele.Text = "Spárovaní dodavatelé: " + Dodavatel.getDodavatele(',');

            // DODAVATELE
            cmbDodavatele.ItemsSource = Dodavatel.getDodavatele(true,true);

            // INFO
            lbluzivatel.Content = konfigurece.Uzivatel;
            lblverze.Content = konfigurece.Verze;
        }

        private void tabControl1_Unloaded(object sender, RoutedEventArgs e)
        {

        }
        #endregion

        #region UDALOSTI KONTROLU
        private void textBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            konfigurece.Ftp1User = textBox1.Text;
        }

        private void passwordBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            konfigurece.Ftp1Psw = passwordBox1.Password.ToString();
        }

        private void textBox2_LostFocus(object sender, RoutedEventArgs e)
        {
            konfigurece.Ftp1Host = textBox2.Text;
            cesta = Path.Combine(konfigurece.Ftp1Host,konfigurece.Ftp1PathXml);
        }

        private void textBox3_LostFocus(object sender, RoutedEventArgs e)
        {
            konfigurece.Ftp1PathPictures = textBox3.Text;
        }

        private void textBox4_LostFocus(object sender, RoutedEventArgs e)
        {
            konfigurece.Ftp1PathXml = textBox4.Text;
            cesta = Path.Combine(konfigurece.Ftp1Host,konfigurece.Ftp1PathXml);
        }
        #endregion      

        #region ZALOHA
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            fileBrowserDialog = new FolderBrowserDialog();
            DialogResult result = fileBrowserDialog.ShowDialog();
            if (result.ToString().Equals("OK"))
            {
                tb1.Text = fileBrowserDialog.SelectedPath;
                zalohovat.IsEnabled = true;
                cestaKzaloze = fileBrowserDialog.SelectedPath;
            }
        }

        private void zalohovat_Click(object sender, RoutedEventArgs e)
        {
            bw2.RunWorkerAsync();
        }

        private void zalohuj()
        {
            // nejdriv zkopiruju soubory s Databazi produktu
            if(Directory.Exists(konfigurece.MantCestaKdb))
            {
                // vytvorim slozku
                Directory.CreateDirectory(cestaKzaloze+nazevSlozky);

                string[] soubory = Directory.GetFiles(konfigurece.MantCestaKdb);
                foreach (string s in soubory)
                {
                    string temp = System.IO.Path.GetFileName(s);
                    File.Copy(s, cestaKzaloze + nazevSlozky+"\\"+temp);
                    bw2.ReportProgress(1, temp);
                }
            }

            // zalohuji nastaveni programu
            
            // aktualizuju promennou kategorie
            ListItem[] a = new ListItem[listBox1.Items.Count];
            listBox1.Items.CopyTo(a, 0);
            Kategorie.setKategorie(a);
            
            // ulozim zmeny v settings
            konfigurece.ulozKonfiguraci();
            
            // zapisu do souboru
            using (StreamWriter writter = new StreamWriter(cestaKzaloze + nazevSlozky + "\\MAnt_backup.bu"))
            {
                foreach (SettingsProperty currentProperty in Properties.Settings.Default.Properties)
                {
                    writter.WriteLine("{0}#{1}",currentProperty.Name, Properties.Settings.Default[currentProperty.Name]);
                }
            }
            bw2.ReportProgress(2, "Záloha programu proběhla vpořádku.");
        }
        #endregion

        #region OBNOVENI
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg;
            dlg = new Microsoft.Win32.OpenFileDialog();
            //dlg.Filter = "BU file (*.bu; *.BU)";

            result = dlg.ShowDialog();

            if (result == true)
            {
                tb2.Text = dlg.FileName;
                cestaKobnovovacimusouboru = dlg.FileName;
                obnovitBTN.IsEnabled = true;
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            obnovNastaveni();
        }

        private void obnovNastaveni()
        {
            StreamReader reader = new StreamReader(cestaKobnovovacimusouboru);

            try
            {
                string line = string.Empty;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] temp = line.Split('#');
                    Settings.Default[temp[0]] = temp[1];
                }
                Settings.Default.Save();
                moznostiWindow.InitializeComponent();
                lbl001.Content = "Nastavení bylo obnoveno.";
                lbl001.Foreground = IOproudy.barvaZelena2;
            }
            catch
            {
                lbl001.Content = "Nastala chyba při obnovování.";
                lbl001.Foreground = IOproudy.barvaCervena2;
            }
            finally
            {
                reader.Close();
            }
        }
        #endregion

        #region SPRAVA DATABAZE
        private void openBTN_Click(object sender, RoutedEventArgs e)
        {
            XElement mymusic = XElement.Load(LBabc.SelectedItem.ToString());

            dg1.DataContext = mymusic.Elements("item");            
        }

        private void LBabc_Initialized(object sender, EventArgs e)
        {
            string path = konfigurece.MantSettingsPath + konfigurece.MantCestaKdb;
                
            if (Directory.Exists(path))
            {
                string [] soubory = Directory.GetFiles(path);
                foreach (string s in soubory)
                {
                    FileInfo f = new FileInfo(s);
                    LBabc.Items.Add(f.FullName);
                }
            }
        }

        private void dg1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            DataRowView rowBeingEdited = null;
            DataRowView rowView = e.Row.Item as DataRowView;
            rowBeingEdited = rowView;
        }
        #endregion

        #region PAROVANI
        private void InicializaceParametruNetDirect()
        {
            parametryNetDirect = new Dictionary<int, string>();
            parametryNetDirect.Add(0, "sIdZbozi");
            parametryNetDirect.Add(1, "sKodZbozi");
            parametryNetDirect.Add(2, "sJmenoVyrobku");
            parametryNetDirect.Add(3, "sKratkyPopis");
            parametryNetDirect.Add(4, "sPopis");
            parametryNetDirect.Add(5, "sJmenoVyrobce");
            parametryNetDirect.Add(6, "nZarukaMesicu");
            parametryNetDirect.Add(7, "nDph");
            parametryNetDirect.Add(8, "sDostupnost");
            parametryNetDirect.Add(9, "sDostupnostNazev");
            parametryNetDirect.Add(10, "sDostupnostPopis");
            parametryNetDirect.Add(11, "sJmenoObrazku");
            parametryNetDirect.Add(12, "bAkcni");
            parametryNetDirect.Add(13, "bNejprodavanejsiKategorie");
            parametryNetDirect.Add(14, "bNejprodavanejsiEshop");
            parametryNetDirect.Add(15, "bNovinka");
            parametryNetDirect.Add(16, "bTip");
            parametryNetDirect.Add(17, "nZboziPoradi");
            parametryNetDirect.Add(18, "nAkcniPoradi");
            parametryNetDirect.Add(19, "nNejprodKategPoradi");
            parametryNetDirect.Add(20, "nNejprodEshopPoradi");
            parametryNetDirect.Add(21, "nNovinkaPoradi");
            parametryNetDirect.Add(22, "nTipPoradi");
            parametryNetDirect.Add(23, "bVypnout");
            parametryNetDirect.Add(24, "nDefaultMnozstviDoKosiku");
        }

        private void btn2_Click(object sender, RoutedEventArgs e)
        {
            Nullable<bool> result2;
            Microsoft.Win32.OpenFileDialog dlg2;
            string path2 = string.Empty;

            dlg2 = new Microsoft.Win32.OpenFileDialog();
            dlg2.Filter = "XML dokument (*.xml; *.XML) | *.xml; *.XML | CVS dokument (*.cvs) | *.cvs";

            result2 = dlg2.ShowDialog();

            if (result2 == true)
            {
                tbx2.Text = dlg2.FileName;
                path2 = dlg2.FileName;
                label10.Content = "Soubor " + path2 + " byl načten";
                label10.Foreground = IOproudy.barvaZelena2;
                ukazAtributy(path2);
                lblName.Content = parametryNetDirect[0].ToString();
            }
        }

        private void ukazAtributy(string path2)
        {
            XmlDocument doc = new XmlDocument();

            // nastavit kodovani xml

            try { doc.Load(path2); }
            catch (Exception e)
            {
                IOproudy.PridejChybu(MethodInfo.GetCurrentMethod().Name, e.ToString(), DateTime.Now);
                return;
            }

            // ziskani korenoveho elementu
            XmlNode root = doc.DocumentElement;
            Dictionary<string, string> seznamArtibutu = new Dictionary<string, string>();

            // pruchod vnorenymi uzly korenoveho elementu
            //
            //
            //
            // OSETRIT VNORENE ELEMENTY
            //
            //
            //
            XmlNode node = root.ChildNodes[0];
            XmlNodeList list = doc.SelectNodes("//SHOPITEM")[0].ChildNodes;

            var data = XElement.Load(path2); // change this to reflect location of your xml file
            

            foreach (XmlElement e in node.ChildNodes)
            {
                if(e.HasChildNodes)
                {
                    XmlNodeList temp = e.ChildNodes;
                }
                seznamArtibutu.Add(e.Name, "xxx");
            }
            // naplnim comboboxi ziskanymi daty
            cmbValue.ItemsSource = seznamArtibutu;
        }

        private void BulozitZmeny_Click(object sender, RoutedEventArgs e)
        {
            // nez ulozim, musim zkontrolovat povinne udaje
            if( string.IsNullOrEmpty( TBXdodavatel.Text ))
            {
                label101.Content = "Povinný údaj Jméno dodavatele je prázdný.";
                return;
            }

            // zkontroluju jestli jiz dodavatel se stejnym jmenem neni ulozeny
            List<Dodavatel> temp = Dodavatel.getDodavatele();
            
            foreach(Dodavatel d in temp)
            {
                if (TBXdodavatel.Text.Equals(d.JmenoDodavatele))
                {
                    label101.Content = "Jméno dodavatele již existuje v seznamu dodavatelů.";
                    return;
                }
            }


            // ulozim vsechny hodnoty comboboxu do seznamu a pak to ulozim do settings
            StringBuilder seznam = new StringBuilder();

            

            // ulozim nove vytvorene sparovani do souboru
            ulozParovaniDoSouboru(TBXdodavatel.Text, seznam);
        }

        private void ulozParovaniDoSouboru(string dod, StringBuilder seznam)
        {
            // noveho dodavatele ulozim taky do Settings
            Dodavatel.setDodavatele(new Dodavatel(dod, 0));
            labelDodavatele.Text = Dodavatel.getDodavatele(',');

            // data ulozim do souboru
            using (StreamWriter file = new StreamWriter(konfigurece.MantSettingsPath + konfigurece.MantCestaKparovani + dod + ".par", false))
            {
                file.WriteLine(seznam);
            }

            // informacni vypis
            label101.Foreground = IOproudy.barvaZelena2;
            label101.Content = "Dodavatel " +TBXdodavatel.Text+ " byl uložen.";

            // aktualizuju combobox dodavatelu v zalozce Dodavatele
            cmbDodavatele.ItemsSource = Dodavatel.getDodavatele(true, true);
        }
        #endregion
    }
}
